package com.jianguozh.difs.support.api.ops;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.annotation.WriteLog;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.constant.SecurityConstant;
import com.jianguozh.difs.framework.validator.group.AddGroup;
import com.jianguozh.difs.framework.validator.group.UpdateGroup;
import com.jianguozh.difs.support.api.ops.dto.ClientDto;
import com.jianguozh.difs.support.service.constant.enums.ClientTypeEnum;
import com.jianguozh.difs.support.service.sys.entity.Client;
import com.jianguozh.difs.support.service.sys.service.IClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 应用 前端控制器
 * </p>
 *
 * @author hanrs
 * @since 2022-03-17
 */
@RestController
@RequestMapping("/client")
public class ClientController extends BaseController {

    @Autowired
    IClientService clientService;

    /**
     * 由id获取对象
     */
    @GetMapping("/{id}")
    public R<Client> get(@PathVariable String id) {
        return success(clientService.getById(id));
    }

    /**
     * 新增
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PostMapping("")
    @WriteLog(value = "添加应用")
    public R<Client> add(@RequestBody @Validated(value = {AddGroup.class}) ClientDto clientDto) {
        long count = clientService.count(new LambdaQueryWrapper<Client>().eq(Client::getAppId, clientDto.getAppId()));
        if (count > 0) {
            return failed("已经存在'" + clientDto.getAppId() + "'的应用.");
        }

        count = clientService.count(new LambdaQueryWrapper<Client>().eq(Client::getClientName, clientDto.getClientName()));
        if (count > 0) {
            return failed("已经存在'" + clientDto.getClientName() + "'的应用.");
        }

        Client entity = new Client();
        BeanUtil.copyProperties(clientDto, entity);
        boolean result = clientService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 修改
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PutMapping("")
    @WriteLog(value = "修改应用")
    public R<Client> modify(@RequestBody @Validated(value = {UpdateGroup.class}) ClientDto clientDto) {
        long count = clientService.count(new LambdaQueryWrapper<Client>().eq(Client::getAppId, clientDto.getAppId()).ne(Client::getId, clientDto.getId()));
        if (count > 0) {
            return failed("已经存在'" + clientDto.getAppId() + "'的应用.");
        }

        count = clientService.count(new LambdaQueryWrapper<Client>().eq(Client::getClientName, clientDto.getClientName()).ne(Client::getId, clientDto.getId()));
        if (count > 0) {
            return failed("已经存在'" + clientDto.getClientName() + "'的应用.");
        }

        Client entity = new Client();
        BeanUtil.copyProperties(clientDto, entity);
        boolean result = clientService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 单个删除
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @DeleteMapping("/{id}")
    @WriteLog(value = "删除应用")
    public R<Boolean> delete(@PathVariable String id) {
        boolean result = clientService.removeById(id);
        return result ? success(true) : failed("操作失败.");
    }

    /**
     * 条件分页查询
     */
    @GetMapping("/page-query")
    public R<IPage<Client>> pageQuery(HttpServletRequest request,
                                      @RequestParam(name = "appId", required = false) String appId,
                                      @RequestParam(name = "clientName", required = false) String clientName,
                                      @RequestParam(name = "clientType", required = false) ClientTypeEnum clientType
    ) {

        LambdaQueryWrapper<Client> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(appId))
            lambdaQueryWrapper.like(Client::getAppId, appId);
        if (StrUtil.isNotBlank(clientName))
            lambdaQueryWrapper.like(Client::getClientName, clientName);
        if (null != clientType)
            lambdaQueryWrapper.eq(Client::getClientType, clientType);

        IPage page = resolvePage(request);
        return success(clientService.page(page, lambdaQueryWrapper));
    }

    /**
     * 获取所有
     * @return
     */
    @GetMapping("/all")
    public R<List<Client>> getAll(){
        return success(clientService.list());
    }
}
